package cn.zcy.springboot_springsecurity.service.impl;

import cn.zcy.springboot_springsecurity.domain.Permissions;
import cn.zcy.springboot_springsecurity.domain.Users;
import cn.zcy.springboot_springsecurity.mapper.PermissionsMapper;
import cn.zcy.springboot_springsecurity.mapper.UsersMapper;
import cn.zcy.springboot_springsecurity.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UsersServiceImpl implements IUsersService {
    @Autowired
    UsersMapper usersMapper;

    @Autowired
    PermissionsMapper permissionsMapper;
//    @Autowired
//    PasswordEncoder passwordEncoder;

    @Override
    public Users getByUserName(String username) {
        Users users = usersMapper.selectByUsersName(username);
        return users;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = usersMapper.selectByUsersName(username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (users != null) {
            List<Permissions> permissions = permissionsMapper.selectByUserId(users.getId());
            //设置权限
            permissions.forEach(per -> {
                if (per != null && !StringUtils.isEmpty(per.getPermissionName())) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(per.getPermissionName());
                    authorities.add(grantedAuthority);
                }
            });
            //封装成UserDetails的实现类
//            String p = passwordEncoder.encode(users.getPassword());
            return new User(users.getUsername(), "123456", authorities);
        } else {
            throw new UsernameNotFoundException("用户名不存在");
        }
    }
}
